package com.thd.springboottest.sso.server.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thd.springboottest.sso.server.service.SsoServerService;
import com.thd.springboottest.sso.server.vo.SessionUtil;
import com.thd.springboottest.sso.vo.AuthBean;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * com.thd.springboottest.sso.server.controller.ServerController
 *
 * @author: wanglei62
 * @DATE: 2021/8/20 18:19
 **/
@Controller
@RequestMapping("/ssoserver")
public class SsoServerController {
    @ResponseBody
    @RequestMapping("/login")
    // url : http://127.0.0.1:8899/ssoserver/login?usr=a&pwd=a1234&jumpUrl=http://127.0.0.1:8898/ssoclient/loginCb
    public ResponseEntity login(String usr, String pwd, String jumpUrl, HttpServletResponse response){
        String ssoToken = SsoServerService.login(usr,pwd);
        try {
            response.sendRedirect(jumpUrl + "?ssoToken=" + ssoToken);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.ok("SUCCESS");
    }

    @ResponseBody
    @RequestMapping("/logout/{ssoToken}")
    // url : http://127.0.0.1:8899/ssoserver/logout/ssoToken=f3fadd0a-e6d0-4337-ba66-5f64558525c1
    public ResponseEntity logout(@PathVariable("ssoToken") String ssoToken,@RequestParam(value="jumpUrl",required = false) String jumpUrl){
        SsoServerService.logout(ssoToken);
        if(null != jumpUrl && jumpUrl.length() > 0){
            // 跳转
        }
        System.out.println(SessionUtil.authBeanList);
        return ResponseEntity.ok("SUCCESS");
    }

    @ResponseBody
    @RequestMapping("/showUserOnline")
    // url : http://127.0.0.1:8899/ssoserver/showUserOnline
    public ResponseEntity showUserOnline(){
        return ResponseEntity.ok(SessionUtil.authBeanList);
    }


    @ResponseBody
    @RequestMapping("/checkSsoToken/{ssoToken}")
    // url : http://127.0.0.1:8899/ssoserver/checkSsoToken/xxx
    public ResponseEntity checkSsoToken(@PathVariable("ssoToken") String ssoToken) throws Exception{

        AuthBean authBean = SessionUtil.get(ssoToken);
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(authBean);
        System.out.println("登录人：" + s);
        return ResponseEntity.ok(authBean);
    }


}
